/**
 * Bootstrap 组件封装
 */

(function ($, window, document, undefined) {
    var pluginName = 'cookePageTable';

    //入口方法
    $.fn[pluginName] = function (options) {
        if (this == null) return null;
        if (options == null) return null;
        if (options == undefined) return null;
        token = sessionStorage.getItem('token');
        return new CookePageTable(this, options);
    };

    var CookePageTable = function (element, options) {
        this.options = $.extend(true,
            {}, this.default, options);
        this.init();
    };

    //默认配置
    CookePageTable.prototype.default = {
        URL : '',                               //ajax请求地址
        dialog: {
            domid: undefined,                   //添加/编辑模态对话框
            readonly: [],                       //编辑模态对话框只读字段
            fieldLoader: {},                    //字段动态加载数据
        },

        toolbar: {
            add: undefined,                     //添加按钮用哪个容器
            del: undefined,                     //删除按钮用哪个容器
            edit: undefined,                    //编辑按钮用哪个容器
            domid: undefined,                   //工具按钮用哪个容器
            search: undefined,                  //查找按钮用哪个容器
        },

        table: {
            domid: undefined,                   //数据列表用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            search: false,                      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 5,                       //每页的记录行数（*）
            //pageList: [5, 10, 25, 50, 100],        //可供选择的每页的行数（*）
            strictSearch: false,
            showColumns: false,                 //是否显示所有的列
            showRefresh: false,                 //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            showToggle: false,                  //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                  //是否显示父子表
            columns: [],
        },
    };

	CookePageTable.prototype.getTable = function() {
        return this.table;
    };

    CookePageTable.prototype.refresh = function() {
	    this.table.bootstrapTable('refresh');
    };

	CookePageTable.prototype.ajaxListRequest = function() {
        var me = this;
        var options = me.options.table || {};
        return options.ajax || function (request) {
            $.ajax({
                type : "POST",
                dataType: "json",
                url: me.options.URL + '/listAll',
                contentType: "application/json",
                data: JSON.stringify({
                }),
                headers: {Token: token},
                success: function(data, textstatus, jqxhr) {
                    request.success(data.data, textstatus, jqxhr);
                    me.table.bootstrapTable('load', data.data);
                },

                error: function(jqxhr, textstatus, errorthrown){
                    var data = jqxhr.responseJSON;
                    $.message({type:'error', message:data.msg||data.error});
                }
            });
        };
    };

    CookePageTable.prototype.oprateEvents = function(context) {
        var me = context;
        return {
            "click #tb_edit" : function(e, value, row, index) {
                me.edit([row]);
            },

            "click #tb_delete" : function(e, value, row, index) {
                me.remove([row]);
            },

            "click #tb_search" : function(e, value, row, index) {
                me.search([row]);
            }
        };
    };

    CookePageTable.prototype.editFormatter = function (value, row, index) {
        return '<a id="tb_edit" style="cursor:pointer">' + value + '</a>';
    }

    CookePageTable.prototype.oprateFormatter = function (value, row, index) {
        return [
            '<a id="tb_edit" style="cursor:pointer">编辑</a> ',
            '<a id="tb_delete" style="cursor:pointer">删除</a> ',
        ].join("");
    }
        
	CookePageTable.prototype.init = function () {
        this.init_table();
        this.init_dialog();
        this.init_toolbar();
    }

	CookePageTable.prototype.init_table = function () {
        var me = this;
        var options = $.extend(me.options.table, {
            ajax: me.ajaxListRequest(),//ajax处理函数
            //toolbar: me.options.toolbar.domid,
        });

        for (var i = 0; i < options.columns.length; i++) {
            var f =  options.columns[i];
            /*
            if (f.field == 'appkey' && isNaN(f.formatter)) {
                options.columns[i] = $.extend(
                    options.columns[i], {
                    events: me.oprateEvents(),
                    formatter: me.editFormatter,
                });
            }
            */

            if (f.field == 'operate' && isNaN(f.formatter)) {
                options.columns[i] = $.extend(
                    options.columns[i], {
                    events: f.events(me) || me.oprateEvents(me),
                    formatter: f.formatter || me.oprateFormatter,
                });
            }
        }

        this.table = $(options.domid).bootstrapTable(options);
    };

	CookePageTable.prototype.init_dialog = function () {
        var me = this;
        var dialog = undefined;
        var options = $.extend(
            me.options.dialog, {
            URL: me.options.URL,
            success: function (data, status, request) {
                if (data.code != 200) {
                    $.message({type:'error', message:data.msg||data.error});
                    return;
                }

                $.message({type:'success', message:data.msg||data.error});
                me.dialog.modal('hide')
                me.table.bootstrapTable('refresh');
            },
        });

        if (options.domid != undefined) {
            dialog = $(options.domid);
        }

        this.dialog = dialog;
        if (dialog == undefined) return;
        this.dialogForm = dialog.find('form').cookeForm(options);
    };

	CookePageTable.prototype.init_toolbar = function () {
        var me = this;
        //初始化页面上面的按钮事件
        var options = me.options.toolbar;
        if (options.add != undefined) {
            $(options.add).click(function () {
                me.add();
            });
        }

        if (options.del != undefined) {
            $(options.del).click(function () {
                var arrselections = me.table.bootstrapTable('getSelections');
                if (arrselections.length <= 0) {
                    $.message({type:'warning', message:'请勾选要删除的数据'});
                    return;
                }
                /*
                if (arrselections.length > 1) {
                    $.message({type:'warning', message:'只能勾选一行进行删除'});
                    return;
                }
                */

                me.remove(arrselections);
            });
        }

        if (options.edit != undefined) {
            $(options.edit).click(function () {
                var arrselections = me.table.bootstrapTable('getSelections');
                if (arrselections.length <= 0) {
                    $.message({type:'warning', message:'请勾选要编辑的效数据'});
                    return;
                }
                if (arrselections.length > 1) {
                    $.message({type:'warning', message:'只能勾选一行进行编辑'});
                    return;
                }

                me.edit(arrselections);
            });
        }

        if (options.search != undefined) {
            $(options.search+"Btn").click(function () {
                me.search($(options.search).val());
            });
        }
    };

	CookePageTable.prototype.reset_dialog = function () {
        var me = this;
        var dialog = me.dialog;
        if (dialog == undefined) return;
        var options = me.options.dialog;
        dialog.find('form').get(0).reset();
        for (var i in options.readonly) {
            var key = options.readonly[i];
            var field = dialog.find("#"+key);
            field.attr("disabled", false);
        }

        me.dialogForm.fieldLoader();
        //dialog.find('.selectpicker').selectpicker('val', "");
        var childrens = dialog.find('textarea');
        for (var i = 0; i < childrens.length; i++){
            var elem = childrens[i];
            if (elem.dataset.type == "summernote") {
                $(elem).summernote('code', '');
            }
        }
    };

	CookePageTable.prototype.add = function () {
        var me = this;
        var t = "添加";
        me.reset_dialog();
        
        var dialog = me.dialog;
        if (dialog == undefined) return;
        var options = me.options.dialog;
        dialog.find('.modal-title').text(t);
        if (options.title != undefined) { 
            var t = t + options.title;
            dialog.find('.modal-title').text(t);
        }

        var uniqid = me.options.table.uniqueId
        if (uniqid != undefined) {
            var k = '#' + uniqid;
            var uniqfield = dialog.find(k)
            uniqfield.val('');
        }

        var dialogForm = me.dialogForm;
        if (dialogForm == undefined) return;
        dialogForm.setAction(me.options.URL + '/add');
        dialog.modal();
    };

    CookePageTable.prototype.edit = function (arrselections) {
        var me = this;
        me.reset_dialog();
        var dialog = me.dialog;
        var data = arrselections[0];
        if (dialog == undefined) return;
        var options = me.options.dialog;
        for (var key in data) {
            var field = dialog.find("#"+key);
            if (options.readonly.includes(key)) {
                field.attr("disabled", true);
            }

            var classname = field.attr("class") || '';
            if (classname.indexOf("selectpicker") >= 0) {
                 field.selectpicker('val', data[key]);
                 continue;
            }

            var dataset = field.data() || {};
            if (dataset.type == "summernote") {
                field.summernote('code', decodeURIComponent(data[key]));
                continue;
            }

            field.val(data[key]);
        }

        var t = "编辑";
        dialog.find('.modal-title').text(t);
        if (options.title != undefined) {
            t = t + options.title;
            dialog.find('.modal-title').text(t);
        }

        var dialogForm = me.dialogForm;
        if (dialogForm == undefined) return;
        dialogForm.setAction(me.options.URL + '/modify');
        dialog.modal();
    };

    CookePageTable.prototype.state = function (arrselections) {
        var me = this;
        if (arrselections.length <= 0) {
            $.message({type:'warning', message:'请勾选要编辑的效数据'});
            return;
        }

        if (arrselections.length > 1) {
            $.message({type:'warning', message:'只能勾选一行进行编辑'});
            return;
        }

        $.ajax({
            type: "post",
            dataType: "json",
            headers: {Token: token},
            url: me.options.URL + '/state',
            data: JSON.stringify(arrselections[0]),
            contentType: "application/json",
            success: function (data, status) {
                if (data.code != 200) {
                    $.message({type:'error', message:data.msg || data.error});
                    return;
                }

                $.message({type:'success', message:data.msg || data.error});
                me.table.bootstrapTable('refresh');
            },

            error: function (request, status, error) {
                var data = request.responseJSON;
                $.message({type:'error', message:data.msg || data.error});
            },
        });
    }; // end of page.state

    CookePageTable.prototype.search = function (value) {
        var me = this;
        var filter = {};
        var columns = me.options.table.columns;
        for (var i = 0; i < columns.length; i++) {
            var column = me.options.table.columns[i];
            if (column.filter || false) {
                filter[column.field] = value;
            }
        }

        if (value == "") {
            me.table.bootstrapTable(
                "filterBy"
            );
        } else {
            me.table.bootstrapTable(
                "filterBy", filter,
                {'filterAlgorithm': 'or'}
            );
        }
    };

    CookePageTable.prototype.remove = function (arrselections) {
        var me = this;
        var uniqids = [];
        var options = me.options.table;
        var uniqview = options.uniqdesc || function(row) {
            return row[options.uniqueId];
        };

        for (var i = 0; i < arrselections.length; i++) {
            d = arrselections[i];
            uniqids.push(uniqview(d));
        }

        text = [
            "确定删除",
            "<b><font color=\"red\">",
            uniqids.join(","),
            "</font></b>",
            "吗？"
        ].join(" ");

        swal({
            html: text,             //弹出框里面的提示文本
            type: "warning",        //弹出框类型
            title: "删除提示",      //弹出框的title
            showCancelButton: true, //是否显示取消按钮
            confirmButtonColor: "#DD6B55",//确定按钮颜色
            cancelButtonText: "取消",//取消按钮文本
            confirmButtonText: "是的，确定删除！",//确定按钮上面的文档
        }).then(function(isConfirm) {
            if (isConfirm.value != true) {
                return;
            }

            $.ajax({
                type: "post",
                dataType: "json",
                headers: {Token: token},
                url: me.options.URL + '/delete',
                data: JSON.stringify(arrselections),
                contentType: "application/json",
                success: function (data, status) {
                    if (data.code != 200) {
                        $.message({type:'error', message:data.msg || data.error});
                        return;
                    }

                    $.message({type:'success', message:data.msg || data.error});
                    me.table.bootstrapTable('refresh');
                },

                error: function (request, status, error) {
                    var data = request.responseJSON;
                    $.message({type:'error', message:data.msg || data.error});
                },
            });
        });
    }; // end of function CookePageTable.prototype.remove

})(jQuery, window, document);

